package com.qeado.admin.interceptor;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.qeado.admin.common.BaseConstData;
import com.qeado.admin.model.AdminAccount;
import com.qeado.admin.model.Menu;

@Service
public class AuthorityInterceptor extends HandlerInterceptorAdapter {
	
	/**
	 * 该类用来验证请求是否在当前用户权限范围之类，不是则转向登录页面。
	 * @author Richard
	 * @version 2.0 2011/3/4
	 */
    @SuppressWarnings("unchecked")
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { 
		String uri = request.getRequestURI();
		if("1".equals(request.getParameter("menuFlag"))) {//only validate for menu request
			AdminAccount userInfo = (AdminAccount)request.getSession().getAttribute(BaseConstData.ADMIN_USER);
			List<Menu> menuList = (List<Menu>)request.getSession().getAttribute(BaseConstData.MENU_LIST);
			if(userInfo != null && menuList != null && menuList.size() > 0){
				for(int i=0;i<menuList.size();i++) {
					Menu menu = menuList.get(i);
					if(menu != null && menu.getMenuList() != null) {
						for(int j=0;j<menu.getMenuList().size();j++) {
							Menu innerMenu = menu.getMenuList().get(j);
							if(uri.endsWith(innerMenu.getUrl())) {
								return true;
							}
						}
					}
				}
				try {
					response.sendRedirect(BaseConstData.REDIRECT_PAGE);
					return false;
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				try {
					response.sendRedirect(BaseConstData.REDIRECT_PAGE);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return true;
   }  

}
